package com.witframework.soa.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

public class XmlBuilder {
	private Writer writer;

	public XmlBuilder() {
		this.writer = new StringWriter();
	}

	public XmlBuilder(Writer writer) {
		this.writer = writer;
	}
	
	public void flushBuilder() {
		try {
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	public void closeBuilder() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private XmlBuilder write(String text) {
		try {
			writer.write(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this;
	}
	
	public int length() {
		return writer.toString().length();
	}
	
	public XmlBuilder append(Object text) {
		if (text != null) {
			write(text.toString());
		}
		return this;
	}
	
	public XmlBuilder append(String text) {
		write(text);
		return this;
	}
	
	public XmlBuilder format(int tabs, int newlines) {
		tabs(tabs);
		newlines(newlines);
		return this;
	}
	
	public XmlBuilder tabs(int tabs) {
		for (int i = 0; i < tabs; i++) {
			tab();
		}

		return this;
	}
	
	public XmlBuilder newlines(int newlines) {
		for (int i = 0; i < newlines; i++) {
			newline();
		}

		return this;
	}
	
	public XmlBuilder tab() {
		write("\t");

		return this;
	}

	
	public XmlBuilder newline() {
		write("\n");

		return this;
	}

	
	public XmlBuilder close() {
		write(">");

		return this;
	}

	
	public XmlBuilder xclose() {
		write("/>");

		return this;
	}
	
	public XmlBuilder elementStart(String name){
		write("<");
		write(name);
		
		return this;
	}
	public XmlBuilder elementEnd(String name){
		write("</");
		write(name);
		write(">");
		return this;
	}
	public XmlBuilder attribute(String name,String value){
		write(" ");
		write(name);
		write("=\"");
		write(value);
		write("\"");
		
		return this;
	}
	public String toString() {
		return writer.toString();
	}
}
